// import 'dart:js';

// import 'dart:html';
import 'dart:io';
// import 'dart:js';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:package_info/package_info.dart';

import 'package:path_provider/path_provider.dart';
import 'package:install_plugin/install_plugin.dart';

class Updater extends StatefulWidget {
  //const ExpandedRow({Key? key}) : super(key: key);
  const Updater({Key key}) : super(key: key);
  @override
  _Updater createState() => _Updater();

  // @override
  // Widget build(BuildContext context) {
  //   // TODO: implement build
  //   return _Updater();
  // }

  @override
  void initState() {
    // TODO: implement initState
  }
}

class _Updater extends State<Updater> {
  // static String baseUrl = "http://192.168.68.202:9603";
  static String baseUrl = "http://153.99.98.91:9989";
  static String _version;
  double _progress = 0.0;
  BuildContext context1;
  static String verApi = "liftappwb";
  static String verNum;
  @override
  Widget build(BuildContext context) {
    return InkWell(
        onTap: () {
          setState(() {
            setState(() {
              _click(context);
            });
            // _click(context);
          });
          // _click(context);
        },
        child: Text("更新")
    );
  }

  @override
  void initState() {
    // TODO: implement initState

    print("=====================================");
    super.initState();
    print("init update1");
  }

  void _click(BuildContext context) async {
    context1 = context;
    // print('index$index');
    /// 获取当前版本
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    _version = packageInfo.version;
    print('当前版本:$_version');
    getVersion(_version);
  }

  // 获取版本信息
  void getVersion(String version) async {
    SmartDialog.showLoading();
    var dio = new Dio();
    Map dataUp = {
      "version": version,
      "prjName": verApi,
    };
    Response ret;
    ret = await dio.post("$baseUrl/upload/get-version", data: dataUp);

    if (ret.data["errorCode"] != 0) {
      print(ret.data["errorInfo"]);
      print(ret.data);
      _myToast(ret.data["errorInfo"] ?? "出错");
      return;
    }

    if (!ret.data["flag"]) {
      print(ret.data);
      // _myToast("已经是最新版本");
      SmartDialog.dismiss();
      SmartDialog.showToast("最新版本了");
      return;
    }

    print(ret.data);
    var url = ret.data['url'];

    var fileUrl = "$baseUrl$url";
    print("开始更新: $fileUrl");
    SmartDialog.dismiss();

    _myDialog();
    installApk(fileUrl);
  }

  /// 下载安卓更新包
  Future<File> downloadAndroid(String url) async {
    /// 创建存储文件
    Directory storageDir = await getExternalStorageDirectory();
    String storagePath = storageDir.path;
    File file = new File('$storagePath/1.0.0.apk');

    if (!file.existsSync()) {
      file.createSync();
    }

    try {
      /// 发起下载请求
      Response response = await Dio().get(url,
          onReceiveProgress: showDownloadProgress,
          options: Options(
            responseType: ResponseType.bytes,
            followRedirects: false,
          ));
      file.writeAsBytesSync(response.data);
      return file;
    } catch (e) {
      print(e);
    }
  }

  /// 下载进度
  void showDownloadProgress(num received, num total) {
    if (total != -1) {
      print(_progress);

      setState(() {
        _progress = double.parse('${(received / total).toStringAsFixed(2)}');
      });

      if (_progress == 1) {
        // installApk();
        print("下好了");
        SmartDialog.dismiss();
      }
    }
  }

  /// 安装apk
  Future<Null> installApk(String url) async {
    File _apkFile = await downloadAndroid(url);
    // return;
    String _apkFilePath = _apkFile.path;

    if (_apkFilePath.isEmpty) {
      print('文件丢失');
      _myToast("文件丢失");
      return;
    }

    InstallPlugin.installApk(_apkFilePath, "com.yywis.elevator").then((result) {
      print('install apk $result');
    }).catchError((error) {
      print('install apk error: $error');
    });
  }

  /// toast
  _myToast(String str) async {
    Fluttertoast.showToast(
        msg: str,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.black,
        textColor: Colors.white,
        fontSize: 16.0);
    return;
  }

  /// show dialog
  _myDialog() {
    var custom = Container(
      height: 180,
      width: 180,
      decoration: BoxDecoration(
        // color: Colors.black,
        borderRadius: BorderRadius.circular(20),
      ),
      alignment: Alignment.center,
      child: new CircularProgressIndicator(
        strokeWidth: 4.0,
        backgroundColor: Colors.grey,ed
        // value: _progress,
        valueColor: new AlwaysStoppedAnimation<Color>(Colors.black),
      ),
    );
    SmartDialog.show(widget: custom, isLoadingTemp: false);
  }
}
